package comWorld.social;

import java.util.List;

import com.gjs.tools.JDBC.JDBCTools;

import comWorld.user.UserInfo;
import comWorld.user.UserStatus;

public class SocialManage {
	public static final String FRIEND_TYPE_ONE = "follow";
	public static final String FRIEND_TYPE_TWO = "fans";
	
	public static List<UserInfo> getFriends(String type, int id) {
		
		String sql = "select id, login_email loginEmail, password, user_name name, sex, address," + 
				" bothday, PERSONALITY_LABEL label, head_image headImage from user_info where id in ";
		
		if (type.equals(FRIEND_TYPE_ONE))
			sql += "(select friend_id from social_info where user_id = ?)";
		else if (type.equals(FRIEND_TYPE_TWO))
			sql += "(SELECT user_id FROM social_info WHERE friend_id = ?)";
		
		List<UserInfo> friends = JDBCTools.getObjects(UserInfo.class, sql, id);
		
		return friends;
	}
	
	public static SocialInfo getFriendsCount(int id) {
		SocialInfo socialInfo = new SocialInfo();
		socialInfo.setId(id);
		socialInfo.setFellowsCount(getFriendsCount(FRIEND_TYPE_ONE, id));
		socialInfo.setFansCount(getFriendsCount(FRIEND_TYPE_TWO, id));
		return socialInfo;
	}
	
	public static int getFriendsCount(String type, int id) {
		String sql = "";
		if (type.equals(FRIEND_TYPE_ONE))
			sql = "SELECT COUNT(friend_id) FROM social_info WHERE user_id = ?";
		else if (type.equals(FRIEND_TYPE_TWO))
			sql = "SELECT COUNT(user_id) FROM social_info WHERE friend_id = ?";
		return JDBCTools.getValue(sql, id, type);
	}
	
	public static boolean judgeUserHasFollowed(UserStatus visitorStatus, SocialInfo socialInfo, int userId) {
		boolean followed = false;
		if (visitorStatus.isLogin()) {
			for (UserInfo fans : socialInfo.getFans()) {
				if (fans.getId() == visitorStatus.getId())
					followed = true;
			}
		}
		return followed;
		
	}
	
	public static int deleteFriend(int userId, int friendId, String type) {
		String sql = "";
		if (type.equals(FRIEND_TYPE_ONE))
			sql = "DELETE FROM social_info WHERE user_id = ? AND friend_id = ?";
		return JDBCTools.update(sql, userId, friendId);
	}
	
	public static int addFriend(int userId, int friendId) {
		String sql = "INSERT INTO social_info VALUES(?,?)";
		return JDBCTools.insert(sql, userId, friendId);
	}
}
